package com.weareint.common.utils;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;
import java.util.regex.Pattern;

public abstract class PasswordUtil {

    private static final String NONCE_STR = "bc8c46cdw33cc1048c9aaca05bbb116a103";

    private static final String DEFAULT_PWD = "qwertyuiop";

    /**
     * <pre>
     *      获取同默认密码
     * </pre>
     * @return
     */
    public static String getEncodedDefaultPwd() {
        return encode(DEFAULT_PWD);
    }

    /**
     * <pre>
     *      检查密码复杂度，数字，大小写，其他字符
     * </pre>
     * @param pwd
     * @return
     */
    @SuppressWarnings({"AlibabaAvoidPatternCompileInMethod", "AlibabaUndefineMagicConstant"})
    public static boolean checkPwdComplexity(String pwd) {
        if (null == pwd || "".equals(pwd.trim()) || pwd.length() < 10) {
            return false;
        }
        Pattern numberPattern = Pattern.compile("\\d");
        Pattern lower = Pattern.compile("[a-z]");
        Pattern upper = Pattern.compile("[A-Z]");
        boolean numberFound = numberPattern.matcher(pwd).find();
        boolean lowerFound = lower.matcher(pwd).find();
        boolean upperFound = upper.matcher(pwd).find();
        String replaced = pwd.replaceAll("\\d", "").replaceAll("[a-z]", "").replaceAll("[A-Z]", "");
        return numberFound && lowerFound && upperFound && replaced.length() > 0;
    }

    /**
     * <pre>
     *      用户密码加密
     * </pre>
     * @param password 用户明文密码
     * @return 用户密文密码（SHA1），加盐
     */
    public static String encode(String password) {
        return DigestUtils.sha1Hex(passwordWithSalt(password));
    }

    /**
     * <pre>
     *      用户明文密码是否与密文密码匹配
     * </pre>
     * @param password 用户明文密码
     * @param encodedPassword 用户密文密码
     * @return true-匹配，false-不匹配
     */
    public static boolean matches(String password, String encodedPassword) {
        return Objects.equals(encode(password), encodedPassword);
    }

    /**
     * <pre>
     *      密码加盐
     * </pre>
     * @param password 用户明文密码
     * @return 加盐后的密码
     */
    private static String passwordWithSalt(String password) {
        String userHash = DigestUtils.md5Hex(NONCE_STR);

        final int hashCode = Math.abs(password.hashCode());
        String salt1 = StringUtils.left(userHash, hashCode % userHash.length());
        String salt2 = StringUtils.right(userHash, userHash.length() - salt1.length());

        return String.format("%s%s%s", salt1, password, salt2);
    }
}
